<template>
  <div class="profile-container">
    <div class="header">
      <h1>个人中心</h1>
      <el-button type="danger" @click="handleLogout">退出登录</el-button>
    </div>

    <el-card class="profile-card">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息">
          <el-form :model="userInfo" class="info-form">
            <el-form-item label="用户名" disabled>
              <el-input v-model="userInfo.username" disabled />
            </el-form-item>
            <el-form-item label="昵称">
              <el-input v-model="userInfo.nickname" />
            </el-form-item>
            <el-form-item label="邮箱" disabled>
              <el-input v-model="userInfo.email" disabled />
            </el-form-item>
            <el-form-item label="电话">
              <el-input v-model="userInfo.phone" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updateUserInfo">保存修改</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="修改密码">
          <el-form :model="passwordForm" :rules="passwordRules" ref="passwordRef">
            <el-form-item label="原密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" type="password" />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="updatePassword">修改密码</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '../utils/request'

const userInfo = ref({})
const activeTab = ref('0')
const router = useRouter()
const passwordRef = ref(null)

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次密码输入不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取当前用户信息
onMounted(() => {
  const storedUser = localStorage.getItem('userInfo')
  if (storedUser) {
    userInfo.value = JSON.parse(storedUser)
    fetchUserDetail()
  } else {
    router.push('/login')
  }
})

// 获取用户详细信息
const fetchUserDetail = async () => {
  try {
    const response = await request.post('/getUserDetail', {
      userId: userInfo.value.user_id
    })
    if (response.code === 200) {
      userInfo.value = response.data
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

// 更新用户信息
const updateUserInfo = async () => {
  try {
    const response = await request.post('/updateUserInfo', userInfo.value)
    if (response.code === 200) {
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
      ElMessage.success('信息更新成功')
    } else {
      ElMessage.error(response.msg || '更新失败')
    }
  } catch (error) {
    ElMessage.error('更新失败，请重试')
  }
}

// 更新密码
const updatePassword = async () => {
  passwordRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await request.post('/updatePassword', {
          userId: userInfo.value.user_id,
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })
        if (response.code === 200) {
          ElMessage.success('密码修改成功，请重新登录')
          localStorage.removeItem('userInfo')
          router.push('/login')
        } else {
          ElMessage.error(response.msg || '修改失败')
        }
      } catch (error) {
        ElMessage.error('修改失败，请重试')
      }
    }
  })
}

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('userInfo')
  ElMessage.success('已退出登录')
  router.push('/login')
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.profile-card {
  margin-top: 20px;
}

.info-form {
  margin-top: 20px;
  max-width: 600px;
}
</style>